package com.firmboy.thread.forkJoin;

import org.junit.Test;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * java并行计算框架测试
 *
 * @author firmboy
 * @create 2018-05-18 下午2:00
 **/
public class ForkJoinTest {


    @Test
    public void test(){
        System.out.println();
    }


    @Test
    public void fork() throws ExecutionException, InterruptedException {
        int length = 1000000;
        int[] arr = new int[length];

        int i = 0;
        while(i<length){
            arr[i++] = (int)(Math.random()*100);
        }

        SumTask sumTask = new SumTask(arr, 0, arr.length - 1);

        long start = System.currentTimeMillis();

        ForkJoinPool pool = new ForkJoinPool();

        pool.submit(sumTask);

        Integer result = sumTask.get();

        long end = System.currentTimeMillis();

        System.out.println(String.format("结果%s耗时%sms",result,end-start));


    }

}

class SumTask extends RecursiveTask<Integer>{


    private static int THRESHOLD = 500000;

    private int[] array;

    private int low;

    private int high;

    SumTask(int[] array,int low,int high){
        this.array = array;
        this.low = low;
        this.high = high;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        if(high-low<THRESHOLD){
            for (int i=low;i<high;i++){
                sum = sum+array[i];
            }
        }else {
            int mid = (low+high)>>>1;
            SumTask left = new SumTask(array,low,mid);
            SumTask right = new SumTask(array,mid+1,high);

            left.fork();
            right.fork();


            sum = Integer.sum(left.join(),right.join());
        }
        return sum;
    }
}
